<template>
    <div class="card-page">

        <el-card shadow="always">

            <template #header><span>导出</span></template>
            <kv label="k8s空间">
                <selector v-model="info.namespace" url="/dev/cluster-info/list?take=99" fields="code,name"
                          chk="*"></selector>
                <el-tag :key="info.namespace">{{ info.namespace }}</el-tag>
            </kv>

            <kv label="k8s服务" v-if="info.namespace">
                <k8s-ref v-model="k8sServices" :name="info.namespace + ' 名称空间的服务' " class="flex"
                         :namespace="info.namespace" multi
                ></k8s-ref>
            </kv>

            <kv>
                <template #k>
                <span class="k">
                    <div>mongo数据库 <el-switch v-model="info.mongo_enabled"></el-switch> </div>
                </span></template>
                <div class="flex" v-if="info.mongo_enabled">
                    <div>
                        <div> host:
                            <el-input v-model="info.mongo.host"/>
                        </div>
                        <div style="margin-left: 10px"> port:
                            <el-input v-model="info.mongo.port"/>
                        </div>
                    </div>
                    <div>
                        <div> user:
                            <el-input v-model="info.mongo.user"/>
                        </div>
                        <div style="margin-left: 10px"> password:
                            <el-input v-model="info.mongo.password"/>
                        </div>
                    </div>
                    <div style="width: 100%">
                        dbs:
                        <el-input v-model="info.mongo.dbs"/>
                    </div>

                    <!--                    <div style="width: 100%">-->
                    <!--                        image:-->
                    <!--                        <el-input v-model="info.mongo.targetDockerImage">-->
                    <!--                        </el-input>-->
                    <!--                    </div>-->
                </div>
            </kv>

            <kv>
                <template #k>
                <span class="k">
                    <div>mysql数据库 <el-switch v-model="info.mysql_enabled"></el-switch> </div>
                </span></template>
                <div class="flex" v-if="info.mysql_enabled">
                    <div>
                        <div> host:
                            <el-input v-model="info.mysql.host"/>
                        </div>
                        <div style="margin-left: 10px"> port:
                            <el-input v-model="info.mysql.port"/>
                        </div>
                    </div>
                    <div>
                        <div> user:
                            <el-input v-model="info.mysql.user"/>
                        </div>
                        <div style="margin-left: 10px"> password:
                            <el-input v-model="info.mysql.password"/>
                        </div>
                    </div>
                    <div style="width: 100%">
                        dbs:
                        <el-input v-model="info.mysql.dbs"/>
                    </div>

                    <!--                    <div style="width: 100%">-->
                    <!--                        image:-->
                    <!--                        <el-input v-model="info.mysql.targetDockerImage">-->
                    <!--                        </el-input>-->
                    <!--                    </div>-->
                </div>
            </kv>
            <kv label="分包大小(Mb)">
                <el-input v-model="info.size"></el-input>
            </kv>

            <div style="text-align: center;margin: 10px">
                <el-button size="large" type="primary" @click="ok_click">导 出</el-button>
                <el-button @click="log_click">日志</el-button>
            </div>
        </el-card>


        <div v-if="logs.pendding">队列中...</div>
        <el-steps :active="$data.logs.step" v-if="$data.logs?.steps?.length" finish-status="success" process-status="wait"
                  style="margin: 20px;" :key="$data.logs.version">
            <el-step :title="item.title" v-for="(item,index) in $data.logs.steps" :key="index" @click.native="pop_msg(item)"
                     :status="item.status"
            ></el-step>
        </el-steps>

        <div v-if="$data.appDeploySetting?.id">
            下载完成后，

            <a target="jenkins"
               :href="$data.appDeploySetting.jenkinsServer.jenkinsHttpUrl + '/job/k8s-ops-export/' + $data.result.jenkins_job_number + '/ws' "
               v-if="$data.result?.jenkins_job_number">打开Jenkins</a>
            <a target="jenkins" :href="$data.appDeploySetting.jenkinsServer.jenkinsHttpUrl + '/job/k8s-ops-export/' "
               v-else>打开Jenkins</a>
            , 登录 （
            <el-tag>{{ $data.appDeploySetting.jenkinsServer.userName }}</el-tag>
            /
            <el-tag>{{ $data.appDeploySetting.jenkinsServer.password }}</el-tag>
            ） 并下载文件
        </div>

        <el-dialog :title="$data.log.title" v-model="$data.log_visible" width="80vw" height="80vh">
            <pre v-html="$data.log.content" style="overflow: auto;"/>
        </el-dialog>
    </div>
</template>

<script setup>
/**
 * Created by CodeGenerator  at 2021-04-13 19:37:26
 */

import k8sRef from "../k8s/k8s-deployment-ref.vue"




defineOptions({
    name: "export",
    inheritAttrs: true,
});

//定义 vue2的this,当前组件
const $self = getCurrentInstance();

//定义 $attrs
const $attrs = useAttrs();


//定义data
const $data = reactive({
    appDeploySetting: {},
    result: {jenkins_job_number: 0, logId: ""},
    timer_id: 0,
    log_visible: false,
    logs: {steps: [], result: "", version: 0},
    log: {},
    k8sServices: [],
    info: {
        k8sServices: [],
        mongo_enabled: false,
        mysql_enabled: false,
        mongo: {dbs: "", host: "", port: 27017, user: "root", password: "", dockerImage: ""},
        mysql: {dbs: "", host: "", port: 3306, user: "root", password: "", dockerImage: ""},
        size: 2000
    }, //子对象需要声明。
});

const info = $computed(() => $data.info);

const $props = defineProps({
    action: {type: String},
    id: {type: String}
});

var next_log_all_stage = true;
const list = ref();

//定义事件
const $emit = defineEmits(["update:modelValue", "loaded"]);

const action = $computed(function () {
    return $props.id ? "edit" : "add";
});
const action_name = $computed(function () {
    return {add: "添加", edit: "修改"}[$props.action]
});

const log_click = function () {
};
const ok_click = function () {
    jv.$saveData("info", $data.info)
    jv.$saveData("k8sServices", $data.k8sServices)
    var body = JSON.clone($data.info);
    if (!body.mongo_enabled) {
        delete body.mongo;
    }
    if (!body.mysql_enabled) {
        delete body.mysql;
    }
    delete body.mongo_enabled;
    delete body.mysql_enabled;
    jv.$http.post("/ops/jenkins-ops/export-job", body)
        .then(res => {
            var json = res.data.data;
            $data.result = {jenkins_job_number: json.number, logId: json.code}
            get_log();
            jv.info("成功! 生成 k8s-ops-export");
        });
};
const open_jenkins = function () {
//http://192.168.5.63:8080/job/k8s-ops-export/34/execution/node/3/ws/
    window.open($data.appDeploySetting.jenkins.jenkinsHttpUrl + "/job/k8s-ops-export/" + $data.result.jenkins_job_number + "/ws")
};
const pop_msg = function (item) {
    $data.log = item;
    $data.log_visible = true;
};
const get_log = async function (option) {
    if ($data.timer_id) {
        clearTimeout($data.timer_id);
    }
    if ($data.log_loading) {
        return;
    }
    var getRow = function (row) {
        var status = "wait";
        if (row.successful === true) {
            status = "success"
        } else if (row.successful === false) {
            status = "error"
        }
        return {title: row.name, content: row.content, status: status}
    }
    var p = {};
    if (!next_log_all_stage && $data.logs.steps.length && $data.logs.steps.getLast().status == "wait") {
        p.lastStage = true;
    }
    var catchAction = async function (e) {
        if (e instanceof Error) {
            jv.error(e.message)
            return;
        }
        if (e.response && e.response.status == 200) {
            return;
        }
        if ($data.timer_id) {
            clearTimeout($data.timer_id);
        }
        $data.timer_id = await jv.sleep(3000);
        await get_log(option);
    }
    var res;
    try {
        $data.log_loading = true;
        res = await jv.$http.post("/ops/jenkins-ops/last-log", p);
        $data.log_loading = false;
        if (!res.data.data) {
            jv.warn("服务器没有返回内容")
            return;
        }
        if (res.data.data && res.data.data.length) {
            $data.logs.pendding = false;
        }
        if (next_log_all_stage) {
            next_log_all_stage = false;
        }
        var rows = res.data.data.map(it => getRow(it))
        if (p.lastStage) {
            var lastStep_new = rows.getLast();
            if (lastStep_new) {
                var index = $data.logs.steps.IndexOf(it => it.title == lastStep_new.title);
                if (index < 0) {
                    next_log_all_stage = true;
                    $data.logs.steps.forEach(it => {
                        it.status = "success"
                    });
                    $data.logs.steps.push(lastStep_new);
                } else {
                    $data.logs.steps.splice(index, 1, lastStep_new);
                }
            } else {
                next_log_all_stage = true;
            }
        } else {
            $data.logs.steps = rows;
            $data.logs.result = res.data.value;
            $data.logs.step = $data.logs.steps.length;
            if (res.data.value === true) {
                return
            } else if (res.data.value === false) {
                return
            }
        }
        $data.logs.version++;
        if ($data.timer_id) {
            clearTimeout($data.timer_id);
        }
        $data.timer_id = await jv.sleep(3000);
        await get_log(option);
    } catch (e) {
        await catchAction(e);
    }
};

onMounted(function () {
    jv.$loadData("info", v => $data.info = v)
    jv.$loadData("k8sServices", v => $data.k8sServices = v)
    jv.$http.post("/dev/app-deploy-setting/current").then(res => {
        $data.appDeploySetting = res.data.data;

    })
})

watch(k8sServices, function (v) {
    $data.info.k8sServices = v.map(it => it.name);
}, {immediate: true, deep: true});

</script>

<style scoped lang="scss">
.flex {
    background-color: #fffded;
    padding: 6px;
    border-radius: 8px;
    border: dashed 1px #8ad0f2;
    display: flex;
    flex-wrap: wrap;
}

.flex > div {
    margin: 3px;
}

.flex > div, .flex > div > div {
    display: inline-flex;
    align-items: center;
}
</style>
